import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/models/merchant.dart';
import 'package:merchants/providers/providers.dart';

class MerchantSelectionScreen extends ConsumerStatefulWidget {
  const MerchantSelectionScreen({super.key});

  @override
  MerchantSelectionScreenState createState() => MerchantSelectionScreenState();
}

class MerchantSelectionScreenState
    extends ConsumerState<MerchantSelectionScreen> {
  final TextEditingController _searchController = TextEditingController();
  List<Merchant> _searchResults = [];
  bool _isSearching = false;
  Timer? _debounceTimer;

  @override
  void initState() {
    super.initState();
    _searchController.addListener(_onSearchChanged);
  }

  void _onSearchChanged() async {
    _debounceTimer?.cancel();
    final query = _searchController.text.trim();
    if (query.isEmpty) {
      setState(() {
        _searchResults = [];
        _isSearching = false;
      });
      return;
    }
    _debounceTimer = Timer(const Duration(milliseconds: 500), () async {
      setState(() {
        _isSearching = true;
      });

      try {
        // 向后端查询商户
        final results = await ref
            .read(merchantServiceProvider)
            .fetchMerchants(keyword: query);
        if (mounted) {
          setState(() {
            _searchResults = results;
            _isSearching = false;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _searchResults = [];
            _isSearching = false;
          });
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('搜索失败：${e.toString()}')));
        }
      }
    });
  }

  @override
  void dispose() {
    _debounceTimer?.cancel();
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('选择商户'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 搜索框
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索店名、小程序名或法人姓名',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                suffixIcon:
                    _isSearching
                        ? Padding(
                          padding: const EdgeInsets.all(12.0), // 调整内边距以居中
                          child: SizedBox(
                            width: 16, // 减小宽度
                            height: 16, // 减小高度
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: Theme.of(context).primaryColor, // 与主题颜色一致
                            ),
                          ),
                        )
                        : null,
              ),
            ),
            const SizedBox(height: 10),
            // 搜索结果下拉框
            if (_searchResults.isNotEmpty)
              Card(
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: _searchResults.length,
                  itemBuilder: (context, index) {
                    final merchant = _searchResults[index];
                    return ListTile(
                      title: Text(merchant.name),
                      onTap: () {
                        // 跳转到商户信息页面
                        context.push('/merchant/join', extra: merchant);
                      },
                    );
                  },
                ),
              ),
            const Spacer(),
            // 创建新商户按钮
            _buildSelectionCard(
              context,
              icon: Icons.store_rounded,
              title: '创建新商户',
              subtitle: '您是新商户的所有者或管理者',
              onTap: () => context.push('/merchant/create'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSelectionCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Icon(icon, size: 40, color: Theme.of(context).primaryColor),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      subtitle,
                      style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                    ),
                  ],
                ),
              ),
              const Icon(Icons.chevron_right_rounded),
            ],
          ),
        ),
      ),
    );
  }
}
